//
//  ConfirmBillVc.m
//  Courses
//
//  Created by xxx on 15/1/25.
//  Copyright (c) 2015年 wtf. All rights reserved.
//

#import "ConfirmBillVc.h"
#import "UILabel+AutoSize.h"

#import "SubmitOrderVc.h"
#import "WTFRect.h"


#import "PXHStringComparison.h"
#import "UserCreditVoucher.h"
#define RATIO 10
@implementation ConfirmBillVc
{
    UIScrollView* _backScrollView;
    UITextField *_txtSalesCode;
    UITextField* _nameTextFiled;
    UIView* _saleView;
    UIView* _invoiceView;
    float _invoiceHeght;
    float _saleHeght;
    UIView* _sureView;
    UISwitch* _saleSwith;
    UISwitch* _invoceSwith;
    UIView* _allInvoceVC;
    UITextField* _saleText;
    UILabel* _shiFuLabel;
    UITextField* _consulaiTant;
    UITextField* _taiTouText;
    UITextField* _diZhiText;
    float         _zongE;
    float         _youHui;
    float         _shiFu;
    UILabel*      _shifuTxt;
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    CGRect backFrame = CGRectMake(0, 0, DEFAULT_WIDTH, DEFAULT_HEIGHT * 2.0);
    _backScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, DEFAULT_WIDTH, DEFAULT_HEIGHT + 79)];
    _backScrollView.delegate = self;
    [self.view addSubview:_backScrollView];
    _backScrollView.contentSize = backFrame.size;
    self.title = @"确认订单";
    [self drawView];
    //初始化数据模型
    _order = [[SubmitOrder alloc]init];
    //添加一个点击手势  回收键盘
    UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];
    [self.view addGestureRecognizer:tap];
}
-(void)tapAction{
    [self.view endEditing:YES];
}
//限制x轴不能动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGPoint point = scrollView.contentOffset;
    
    // 限制y轴不动
    point.x = 0.f;
    scrollView.contentOffset = point;
}


- (void)drawView
{
    CGFloat x = 20, y = 0;
    CGFloat width = DEFAULT_WIDTH - 40, heightRow = 40, heightRowS = 30, heightSectionHeader = 20;
    
    // 课程信息
    CGRect courseInfoRect = AutoRectMake(x, y, width, heightRow, WTFAutoLayoutTypePic);
    
    UILabel *lblCourseInfo = [[UILabel alloc] initWithFrame:courseInfoRect];
    lblCourseInfo.text = @"课程信息";
    [_backScrollView addSubview:lblCourseInfo];
    [self addLineBelowView:lblCourseInfo];
    
    CGRect courseNameRect = courseInfoRect;
    courseNameRect.origin.y += AutoFloat(heightRow) + RATIO;
    UILabel *lblCourseName = [[UILabel alloc] initWithFrame:courseNameRect];
    lblCourseName.text = _course.courseName;
    [_backScrollView addSubview:lblCourseName];
    [self addLineBelowView:lblCourseName];
    
    CGRect courseClsDateRect = courseNameRect;
    courseClsDateRect.origin.x += AutoFloat(width / 2 + 50) + RATIO;
    UILabel *lblCourseClsDate = [[UILabel alloc] initWithFrame:courseClsDateRect];
    NSString* time = [_course.courseClasses[_course.selectedClsIndex - 1] classOpenDate];
    NSArray* timeArray = [time componentsSeparatedByString:@" "];
//    lblCourseClsDate.text = [_course.courseClasses[_course.selectedClsIndex - 1] classOpenDate];
    lblCourseClsDate.text = timeArray[0];
    [_backScrollView addSubview:lblCourseClsDate];
    
    CGRect coursePriceRect = courseNameRect;
    coursePriceRect.origin.y += AutoFloat(heightRow) + RATIO;
    UILabel *lblCoursePrice = [[UILabel alloc] initWithFrame:coursePriceRect];
    lblCoursePrice.textAlignment = NSTextAlignmentRight;
    lblCoursePrice.text = [NSString stringWithFormat:@"总价 : ￥%@", [_course.courseClasses[_course.selectedClsIndex - 1] classPrice]];
    [_backScrollView addSubview:lblCoursePrice];
    
    
    // 账号信息
    CGRect rectAccountInfo = coursePriceRect;
    rectAccountInfo.origin.x = 0;
    rectAccountInfo.size.width = AutoFloat(DEFAULT_WIDTH);
    rectAccountInfo.origin.y += AutoFloat(heightRow) + RATIO;
    rectAccountInfo.size.height = AutoFloat(heightSectionHeader);
    UILabel *lblAccountInfo = [[UILabel alloc] initWithFrame:rectAccountInfo];
    lblAccountInfo.textAlignment = NSTextAlignmentCenter;
    lblAccountInfo.textColor = [UIColor whiteColor];
    lblAccountInfo.backgroundColor = [WTFColors defaultBarColor];
    lblAccountInfo.text = @"账号信息";
    [_backScrollView addSubview:lblAccountInfo];
    
    CGRect rectMobile = coursePriceRect;
    rectMobile.origin.y += AutoFloat(heightRow + heightSectionHeader) + RATIO +5;
    rectMobile.size.height = AutoFloat(heightRowS);
    UILabel *lblMobile = [[UILabel alloc] initWithFrame:rectMobile];
    lblMobile.text = [NSString stringWithFormat:@"手机号码 : %@", [[NSUserDefaults standardUserDefaults]objectForKey:@"currentMobile"]];
    [_backScrollView addSubview:lblMobile];
    
    CGRect rectSalesCode = rectMobile;
    rectSalesCode.origin.y += AutoFloat(heightRowS * 2) + RATIO + 5;
    UILabel *lblSalesCodePrefix = [[UILabel alloc] initWithFrame:rectSalesCode];
    lblSalesCodePrefix.text = @"课程顾问 : ";
    [_backScrollView addSubview:lblSalesCodePrefix];
//    [self addLineBelowView:lblSalesCodePrefix];
    [lblSalesCodePrefix autoSetSizeWithInWidth:AutoFloat(width) preferedHeight:AutoFloat(heightRowS)];
    
    CGRect rectTxtSalesCode = rectSalesCode;
    rectTxtSalesCode.origin.x = lblSalesCodePrefix.right;
    rectTxtSalesCode.size.width = AutoFloat(100);
    rectTxtSalesCode.size.height = 24;
    _txtSalesCode = [[UITextField alloc] initWithFrame:rectTxtSalesCode];
    _txtSalesCode.layer.borderColor = [UIColor grayColor].CGColor;
    _txtSalesCode.layer.borderWidth = 1;
    [_backScrollView addSubview:_txtSalesCode];
    UIView* lblSalesCodeLine = [[UIView alloc]initWithFrame:CGRectMake(0, lblSalesCodePrefix.bottom + 8, DEFAULT_WIDTH, 1)];
    lblSalesCodeLine.backgroundColor = [UIColor grayColor];
    [_backScrollView addSubview:lblSalesCodeLine];
    
    
    CGRect rectName = rectMobile;
    rectName.origin.y += AutoFloat(heightRowS) + RATIO;
    UILabel* nameLabel = [[UILabel alloc] initWithFrame:rectName];
    nameLabel.text = @"输入姓名 :";
    [_backScrollView addSubview:nameLabel];
    [nameLabel autoSetSizeWithInWidth:AutoFloat(width) preferedHeight:heightRowS];
    //name text
    CGRect nameTextRect = nameLabel.frame;
    nameTextRect.origin.x = lblSalesCodePrefix.right;
    nameTextRect.size.width = AutoFloat(100);
    nameTextRect.size.height = 24;
    _nameTextFiled = [[UITextField alloc] initWithFrame:nameTextRect];
    _nameTextFiled.layer.borderColor = [UIColor grayColor].CGColor;
    _nameTextFiled.layer.borderWidth = 1;
    [_backScrollView addSubview:_nameTextFiled];
    
    
    //优惠信息
    CGRect saleRect = lblSalesCodePrefix.frame;
    saleRect.origin.x = 15;
    saleRect.origin.y += 24 + 10;
    saleRect.size.width = AutoFloat(150);
    saleRect.size.height = 30;
    UILabel* saleLabel = [[UILabel alloc] initWithFrame:saleRect];
    saleLabel.text = @"优惠信息";
    [_backScrollView addSubview:saleLabel];
    
    //展开按钮
    CGRect saleSwithRect = saleLabel.frame;
    saleSwithRect.origin.x = DEFAULT_WIDTH - 70;
    saleSwithRect.size.width = 50;
    saleSwithRect.size.height = 30;
    _saleSwith = [[UISwitch alloc]initWithFrame:saleSwithRect];
    [_saleSwith setTag:101];
    [_backScrollView addSubview:_saleSwith];
    [_saleSwith addTarget:self action:@selector(swithAction:) forControlEvents:UIControlEventValueChanged];
    [_saleSwith setOn:YES];
    //展开页面
//    _saleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, DEFAULT_WIDTH, 90)];
//    [_backScrollView addSubview:_saleView];
    //划线
    UIView* saleLine = [[UIView alloc]initWithFrame:CGRectMake(0, _saleSwith.bottom + 10, DEFAULT_WIDTH, 1)];
    [_backScrollView addSubview:saleLine];
    saleLine.backgroundColor = [UIColor grayColor];
    //展开界面
    _saleView = [[UIView alloc] initWithFrame:CGRectMake(0, _saleSwith.bottom + 10, DEFAULT_HEIGHT, 90)];
    [_backScrollView addSubview:_saleView];
    UILabel* xueFen = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, 150, 30)];
    xueFen.text = @"使用学分券";
    [_saleView addSubview:xueFen];
    
    _saleText = [[UITextField alloc]initWithFrame:CGRectMake(15, 35, DEFAULT_WIDTH - 115, 30)];
    [_saleView addSubview:_saleText];
    _saleText.placeholder = @"请输入学分券代号";
    _saleText.layer.borderWidth = 1;
    _saleText.layer.borderColor = [UIColor grayColor].CGColor;
    
    
    UIButton* clear = [[UIButton alloc] initWithFrame:CGRectMake(_saleText.right + 5, 35, 40, 30)];
    [_saleView addSubview:clear];
//    clear.backgroundColor = [UIColor orangeColor];
    [clear setTitle:@"删除" forState:UIControlStateNormal];
    [clear setBackgroundImage:[UIImage imageNamed:@"btnBg2"] forState:UIControlStateNormal];
    [clear setTag:1001];
    [clear addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton* use = [[UIButton alloc] initWithFrame:CGRectMake(clear.right + 5, 35, 40, 30)];
    [_saleView addSubview:use];
//    use.backgroundColor = [UIColor orangeColor];
    [use setTitle:@"使用" forState:UIControlStateNormal];
    [use setBackgroundImage:[UIImage imageNamed:@"btnBg2"] forState:UIControlStateNormal];
    [use setTag:1002];
    [use addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIView* saleViewLine = [[UIView alloc]initWithFrame:CGRectMake(0, _saleView.bottom - 1, DEFAULT_WIDTH, 1)];
    [_saleView addSubview:saleViewLine];
    saleViewLine.backgroundColor = [UIColor grayColor];
    
    
    //发票
    // 账号信息
    CGRect invoiceRect = saleLabel.frame;
    invoiceRect.origin.y += 140;
    saleRect.size.width = AutoFloat(100);
    saleRect.size.height = 30;
    _allInvoceVC = [[UIView alloc]initWithFrame:CGRectMake(0, invoiceRect.origin.y, DEFAULT_WIDTH, 120)];
    [_backScrollView addSubview:_allInvoceVC];
//    _allInvoceVC.backgroundColor = [UIColor redColor];
    UILabel* invoiceLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, 100, 30)];
    invoiceLabel.text = @"发票";
    [_allInvoceVC addSubview:invoiceLabel];
    //展开按钮
    _invoceSwith = [[UISwitch alloc]initWithFrame:CGRectMake(DEFAULT_WIDTH - 70, 0, 50, 30)];
    [_invoceSwith setTag:102];
    [_allInvoceVC addSubview:_invoceSwith];
    [_invoceSwith addTarget:self action:@selector(swithAction:) forControlEvents:UIControlEventValueChanged];
    [_invoceSwith setOn:YES];
    //展开页面
    _invoiceView = [[UIView alloc]initWithFrame:CGRectMake(0, 40, DEFAULT_WIDTH, 90)];
    [_allInvoceVC addSubview:_invoiceView];
    UIView* invoiceOne = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEFAULT_WIDTH, 1)];
    [_invoiceView addSubview:invoiceOne];
    invoiceOne.backgroundColor = [UIColor grayColor];
    
    UILabel* taiTou = [[UILabel alloc]initWithFrame:CGRectMake(15, 5, 55, 30)];
    [_invoiceView addSubview:taiTou];
    taiTou.text = @"抬头：";
    _taiTouText = [[UITextField alloc]initWithFrame:CGRectMake(taiTou.right, 10, 150, 30)];
    [_invoiceView addSubview:_taiTouText];
    _taiTouText.placeholder = @"请输入抬头";
    _taiTouText.layer.borderColor = [UIColor grayColor].CGColor;
    _taiTouText.layer.borderWidth = 1;
    
    UILabel* diZhi = [[UILabel alloc]initWithFrame:CGRectMake(15, 45, 55, 30)];
    diZhi.text = @"地址：";
    [_invoiceView addSubview:diZhi];
    _diZhiText = [[UITextField alloc]initWithFrame:CGRectMake(diZhi.right, 45, 200, 30)];
    [_invoiceView addSubview:_diZhiText];
    _diZhiText.placeholder = @"请输入地址";
    _diZhiText.layer.borderWidth = 1;
    _diZhiText.layer.borderColor = [UIColor grayColor].CGColor;

    
    _sureView = [[UIView alloc] initWithFrame:CGRectMake(0, DEFAULT_HEIGHT - 15 + 90, DEFAULT_WIDTH, 85)];
    [_backScrollView addSubview:_sureView];
    UIButton *btnSubmitBill = [[UIButton alloc] initWithFrame:AutoRectMake(DEFAULT_WIDTH - 100, 45, 100, heightRow, WTFAutoLayoutTypePic)];
    [btnSubmitBill setTitle:@"提交订单" forState:UIControlStateNormal];
    [btnSubmitBill setBackgroundImage:[UIImage imageNamed:@"btnBg2"] forState:UIControlStateNormal];
    [btnSubmitBill setBackgroundImage:[UIImage imageNamed:@"btnBg2"] forState:UIControlStateSelected];
    [_sureView addSubview:btnSubmitBill];
    [btnSubmitBill addTarget:self action:@selector(gotoPay) forControlEvents:UIControlEventTouchUpInside];
    UIView* btnLine = [[UIView alloc]initWithFrame:AutoRectMake(0, 0, DEFAULT_WIDTH, 1,WTFAutoLayoutTypeText)];
    btnLine.backgroundColor = [UIColor grayColor];
    [_sureView addSubview:btnLine];
    
    _shiFuLabel = [[UILabel alloc]initWithFrame:AutoRectMake(15, 0, DEFAULT_WIDTH - 30, heightRow,WTFAutoLayoutTypeText)];
    [_sureView addSubview:_shiFuLabel];
    _zongE = [[_course.courseClasses[_course.selectedClsIndex - 1] classPrice] floatValue];
    _youHui = 0.0;
    _shiFu = _zongE - _youHui;
    _shiFuLabel.text = [NSString stringWithFormat:@"总价：%.2f优惠%.2f",_zongE,_youHui];
    _shifuTxt = [[UILabel alloc]initWithFrame:AutoRectMake(15, 25, 200, heightRow, WTFAutoLayoutTypeText)];
    [_sureView addSubview:_shifuTxt];
    _shifuTxt.text = [NSString stringWithFormat:@"实付金额：%.2f",_shiFu];
    
}

-(void)swithAction:(id)sender{
    UISwitch* theSwith = (UISwitch* )sender;
    long int tag = [theSwith tag];
    switch (tag) {
        case 101:
            if ([theSwith isOn]) {
                [_saleView setHidden:NO];
                [_sureView removeFromSuperview];
                if ([_invoceSwith isOn]) {
                    [_sureView setOrigin:CGPointMake(0, DEFAULT_HEIGHT - 15 + 90)];
                    //发票页面
                    float originY = _allInvoceVC.frame.origin.y;
                    [_allInvoceVC removeFromSuperview];
                    [_allInvoceVC setOrigin:CGPointMake(0, originY + 90)];
                    [_backScrollView addSubview:_allInvoceVC];
                }else{
                    [_sureView setOrigin:CGPointMake(0, DEFAULT_HEIGHT - 15 + 90)];
                }
                
                [_backScrollView addSubview:_sureView];
            }else{
                [_saleView setHidden:YES];
                [_sureView removeFromSuperview];
                if ([_invoceSwith isOn]) {
                    [_sureView setOrigin:CGPointMake(0, DEFAULT_HEIGHT - 15 + 90)];
                    //发票页面
                    float originY = _allInvoceVC.frame.origin.y;
                    [_allInvoceVC removeFromSuperview];
                    [_allInvoceVC setOrigin:CGPointMake(0, originY - 90)];
                    [_backScrollView addSubview:_allInvoceVC];                }else{
                    [_sureView setOrigin:CGPointMake(0, DEFAULT_HEIGHT - 15)];
                }
                [_sureView setOrigin:CGPointMake(0, DEFAULT_HEIGHT - 15)];
                [_backScrollView addSubview:_sureView];
            }
            NSLog(@"10101");
            break;
        case 102:
            if ([theSwith isOn]) {
                [_invoiceView setHidden:NO];
                [_sureView removeFromSuperview];
                if ([_saleSwith isOn]) {
                    [_sureView setOrigin:CGPointMake(0, DEFAULT_HEIGHT - 15 + 90)];//这个状态正确
                }else{
                    [_sureView setOrigin:CGPointMake(0, DEFAULT_HEIGHT - 15 + 90)];
                }
                [_backScrollView addSubview:_sureView];
            }else{
                [_invoiceView setHidden:YES];
                [_sureView removeFromSuperview];
                if ([_saleSwith isOn]) {
                    [_sureView setOrigin:CGPointMake(0, DEFAULT_HEIGHT - 15 + 90)];//这个状态正确
                }else{
                    [_sureView setOrigin:CGPointMake(0, DEFAULT_HEIGHT - 15 + 0)];
                }
                [_sureView setOrigin:CGPointMake(0, DEFAULT_HEIGHT - 15)];
                [_backScrollView addSubview:_sureView];
            }
            break;
        default:
            break;
    }

}


- (void)addLineBelowView:(UIView *)view
{
    UIView *line = [[UIView alloc] initWithFrame:AutoRectMake(0, view.bottom + 3, DEFAULT_WIDTH, 1, WTFAutoLayoutTypeBar)];
    line.backgroundColor = [UIColor grayColor];
    [_backScrollView addSubview:line];
}
- (void)addLineAtTopOfView:(UIView *)view
{
    UIView *line = [[UIView alloc] initWithFrame:AutoRectMake(0, view.top, DEFAULT_WIDTH, 1, WTFAutoLayoutTypeBar)];
    line.backgroundColor = [UIColor grayColor];
    [_backScrollView addSubview:line];
}
//进入确认订单页面
-(void)gotoPay{
    NSLog(@"-------");
    [self.view endEditing:YES];
    if (![self isChinesecharacter:_nameTextFiled.text]) {
        ShowTextPromptDelayHide(@"用户姓名只能是中文", 1.0, self.view);
        return;
    }
    
    if ([self chineseCountOfString:_nameTextFiled.text] <= 1) {
        ShowTextPromptDelayHide(@"请输入正确的用户姓名", 1.0, self.view);
        return;
    }
    if(_txtSalesCode.text.length > 0){
        if (![self isChinesecharacter:_txtSalesCode.text]) {
            ShowTextPromptDelayHide(@"课程顾问姓名只能是中文", 1.0, self.view);
            return;
        }
        if ([self chineseCountOfString:_txtSalesCode.text] <= 1) {
            ShowTextPromptDelayHide(@"请输入正确的课程顾问姓名", 1.0, self.view);
            return;
        }
    }
    [self orderAssignment];
    SubmitOrderVc* subVC = [[SubmitOrderVc alloc] initWith:_order Page:1];
    subVC.realMount = _shiFu;
//    subVC.order = _order;
//    subVC.page = 1;
    [self.navigationController pushViewController:subVC animated:NO];
}
-(void)orderAssignment{
    _order.sourceId = @"2";
    _order.deviceNo = @"IOS12345";
    NSDictionary* dicInfo = [[NSBundle mainBundle]infoDictionary];
    _order.version = [dicInfo objectForKey:@"CFBundleShortVersionString"];
    _order.agencyId = @"YX";
    _order.userId = [User currentUser].userId;
    _order.classId = [_course.courseClasses[_course.selectedClsIndex - 1] classId];
    _order.courseId = _course.courseId;
    _order.teacherId = _course.teacherId;
    _order.orderAmount = [_course.courseClasses[_course.selectedClsIndex - 1] classPrice];
    _order.realAmount = [NSString stringWithFormat:@"%.2f",_shiFu];
    _order.discount = [NSString stringWithFormat:@"%.2f",_youHui];
    _order.mobile = [User currentUser].mobile;
    _order.userName = _nameTextFiled.text;
    _order.salesCode = _txtSalesCode.text;//课程顾问
    _order.invoiceType = @"1";
    _order.invoiceTitle = _taiTouText.text;
    _order.invoiceAddress = _diZhiText.text;
    _order.coupons = _saleText.text;
    _order.showPhoneNum = [[NSUserDefaults standardUserDefaults]objectForKey:@"currentMobile"];
}
-(void)buttonAction:(id)sender{
    UIButton* btn = (UIButton* )sender;
    switch ([btn tag]) {
        case 1001:
            _saleText.text = @"";
            break;
        case 1002:
            //使用学分券
        {
            if ([self checkCouponIsTrue:_saleText.text]) {
                UserCreditVoucher* userCrd = [UserCreditVoucher  getUserCreditVoucherWithCouponCode:_saleText.text];
                if (userCrd.result) {
                    _youHui = userCrd.disCount;
                    _shiFuLabel.text = [NSString stringWithFormat:@"总价：%.2f   优惠%.2f",_zongE,_youHui];
                    _shiFu = _zongE - _youHui;
                    _shifuTxt.text = [NSString stringWithFormat:@"实付金额：%.2f",_shiFu];

                }else{
                    NSString* message = [NSString stringWithFormat:@"不正确的学分券，错误信息：%@",userCrd.msg];
                    ShowTextPromptDelayHide(message, 1.0, self.view);
                }
           }else{
                ShowTextPromptDelayHide(@"请输入正确的学分券代号", 1.0, self.view);
         }
        }
            break;
        default:
            break;
    }
}
//判断是否是中文
- (BOOL)isChinesecharacter:(NSString *)string{
    if (string.length == 0) {
        return NO;
    }
    unichar c = [string characterAtIndex:0];
    if (c >=0x4E00 && c <=0x9FA5)     {
        return YES;//汉字
    }
    else
    {
        return NO;//英文
    }
}
//获取中文字符的个数
- (NSInteger)chineseCountOfString:(NSString *)string{
    int ChineseCount = 0;
    if (string.length == 0) {
        return 0;
    }
    for (int i = 0; i<string.length; i++) {
        unichar c = [string characterAtIndex:i];
        if (c >=0x4E00 && c <=0x9FA5)
        {
            ChineseCount++ ;//汉字
        }
    }
    return ChineseCount;
}
//检测优惠券是否合格
-(BOOL)checkCouponIsTrue:(NSString* )coupon{
    NSString* Regex = @"[0-9]{11}";
    NSPredicate* predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",Regex];
    return [predicate evaluateWithObject:coupon];
}
@end
